﻿using System.Linq;
using ExcelAutomator.Configuration;
using ExcelAutomator.Validation;
using Microsoft.Office.Interop.Excel;

namespace ExcelAutomator.Executors.Assert
{
	[Executor(ExecutorName, ExecutorType, ExecutorAction)]
	internal class AssertValueEqualsExecutor: Executor<AssertConfiguration>
	{
		public const string ExecutorName = "Range Assume Executor";
		public const string ExecutorType = "assert";
		public const string ExecutorAction = "equals";

		public override ExecutionResult OnExecute(ExecutionContext context)
		{
			var msg = string.Format("Assert '{0}' equals '{1}'", Configuration.Address, Configuration.Value);

			Worksheet worksheet;
			if (context.TryGetWorksheet(Configuration.Address, Configuration.Context, out worksheet))
			{
				var result = worksheet.get_Range(Configuration.Address, System.Type.Missing).Values<object>().FirstOrDefault();

				if (result != null)
				{
					if (result.Equals(Configuration.Value))
					{
						return ExecutionResult.CreateSuccess(msg, context);
					}
				}
			}
			
			return ExecutionResult.CreateFailure(msg, context);
		}

		public override void OnConfigure(string xmlConfiguration, out AssertConfiguration configuration)
		{
			configuration = ConfigurationBuilder.Build<AssertConfiguration>(xmlConfiguration, Constants.ExecutorExtensionsNamespace);
		}

		#region Validate

		public override void OnValidate(ValidationEngine validationEngine, ExecutionContext context)
		{
			validationEngine.Validate.That.Excel(context.InputWorkbook)
				.WorksheetPreFixIsDefined(Configuration.Address)
				.WorksheetExists(Configuration.Address);
		}

		#endregion

		public override string Name
		{
			get { return ExecutorName; }
		}

		public override string Type
		{
			get { return ExecutorType; }
		}

		public override string ActionId
		{
			get { return ExecutorAction; }
		}
	}
}
